<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/10/18
 * Time: 17:29
 */

namespace app\admin\model;


use think\Model;
use app\admin\validate\Delivery as Vali;

class Delivery extends Model
{
    public function operation($data){
        if(!isset($data['goods'])){
            return echoArr(0, '请勾选需要发货的商品');
        }

        // 发货时间
        $data['create_time'] = time();
        $data['log_time'] = time();

        // 操作记录
        model('OrderAction') -> allowField(true) -> isUpdate(false) -> save($data);

        // 验证
        $validate = new Vali();
        if(!$validate -> check($data)){
            return echoArr(0, $validate->getError());
        }

        // 发货记录
        $result = $this -> allowField(true) -> isUpdate(false) -> save($data);

        // 订单商品发货状态
        $orderGoods = [];
        foreach($data['goods'] as $k => $v){
            $orderGoods[] = ['id' => $k, 'is_send' => $v, 'delivery_id' => $this -> id];
        }
        model('OrderGoods') -> saveAll($orderGoods);

        // 订单发货状态
        $where = [
            'order_id' => $data['order_id'],
            'is_send' => 0
        ];
        $is_send = model('OrderGoods') -> where($where) -> value('id');
        if($is_send){
            $data['shipping_status'] = 2;
        }

        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            $time = '';
            if($data['shipping_status'] == 1){
                $time = $data['create_time'];
            }
            $data['shipping_time'] = $time;
            // 订单修改
            model('Order') -> allowField(true) -> isUpdate(true) -> save($data, ['id' => $data['order_id']]);

            return echoArr(1, '操作成功');
        }
    }
}